package com.common.www.controller.programme;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.domain.PageableRequest;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.Sort;
import com.common.www.bean.entity.programme.ContrastScheme;
import com.common.www.bean.entity.programme.ProjectScheme;
import com.common.www.bean.entity.programme.SupplyCompanyScheme;
import com.common.www.bean.entity.project.Project;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.programme.ContrastSchemeService;
import com.common.www.service.programme.ProjectSchemeService;
import com.common.www.service.programme.SupplyCompanySchemeService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.BiddingCompanyService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.SortUtils;
import com.common.www.utils.office.ImportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/contrastScheme"})
@Api(tags = "MGT 方案管理接口")
public class MGTContrastSchemeController extends DefaultCrudController<ContrastScheme, Long> {
    @Autowired
    private ContrastSchemeService service;
    @Autowired
    private ProjectSchemeService projectSchemeService;
    @Autowired
    private SupplyCompanySchemeService supplyCompanySchemeService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private BiddingCompanyService biddingCompanyService;

    protected IBaseService getService() {
        return service;
    }

    @ApiOperation("查询方案对比内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/getContrastScheme", method = RequestMethod.POST)
    public Result getContrastScheme(Long projectId,Integer jieDuan) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id",projectId);
        PageableRequest pageableRequest = new PageableRequest();
        pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
        //招标方案
        List<ContrastScheme> contrastSchemeList = service.queryToList(hashMap,pageableRequest);
        //外部调研项目方案
        List<ProjectScheme> projectSchemeList = projectSchemeService.queryToList(hashMap,pageableRequest);
        //供应商方案-分阶段
        hashMap.put("jieDuan",jieDuan);
        List<SupplyCompanyScheme> supplyCompanySchemeList = supplyCompanySchemeService.queryToList(hashMap,pageableRequest);
        //组装结果
        Map<String, Object> tempMap = new HashMap<>();
        tempMap = service.getContrastSchemeAll(contrastSchemeList,projectSchemeList,supplyCompanySchemeList);

        return R.ok(tempMap);
    }

    @ApiOperation(value = "导入招标方案", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/importInviteTendersScheme", produces = {"application/json"}, method = RequestMethod.POST)
    public Result importInviteTendersScheme(MultipartFile file, Long projectId) throws Exception {
        Project project = projectService.findOne(projectId);
        HashMap hashMap = new HashMap();
        hashMap.put("project.id",projectId);
        List<ContrastScheme> contrastSchemeList = service.queryToList(hashMap,null);
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook workbook = new ImportExcelUtil().getWorkbook(inputStream, fileName);
        List<ContrastScheme> listImport = service.importSimulate(workbook,project,fileName);

        //整理listImport的数据格式
        List<ContrastScheme> listArrange = new ArrayList<>();
        //同一个项目下contrastSchemeList的条数应该是58条
        if (contrastSchemeList.size() > 0){
            for (ContrastScheme scheme : contrastSchemeList){
                for (ContrastScheme tempImport : listImport){
                    if (scheme.getSort().equals(tempImport.getSort()) && scheme.getDetailsTerm().equals(tempImport.getDetailsTerm())){
                        scheme.setInviteTendersScheme(tempImport.getInviteTendersScheme());
                        scheme.setInviteTendersSchemeFileName(tempImport.getInviteTendersSchemeFileName());
                    }
                }
                listArrange.add(scheme);
            }
        }else {
            String category = null;
            String minorItems = null;
            for (ContrastScheme scheme : listImport){
                String tempCategory = scheme.getCategory();
                String tempMinorItems = scheme.getMinorItems();
                if (StringUtils.isNotEmpty(tempCategory)){
                    category = tempCategory;
                }else {
                    if (StringUtils.isNotEmpty(category)){
                        scheme.setCategory(category);
                    }
                }
                if (StringUtils.isNotEmpty(tempMinorItems)){
                    minorItems = tempMinorItems;
                }else {
                    if (StringUtils.isNotEmpty(minorItems)){
                        scheme.setMinorItems(minorItems);
                    }
                }
                listArrange.add(scheme);
            }
        }
        service.save(listArrange);
        return R.ok();
    }


    @ApiOperation("导出方案对比内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportScheme", method = RequestMethod.GET)
    public Result exportScheme(Long projectId,Integer jieDuan) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id",projectId);
        PageableRequest pageableRequest = new PageableRequest();
        pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
        //招标方案
        List<ContrastScheme> contrastSchemeList = service.queryToList(hashMap,pageableRequest);
        //外部调研项目方案
        List<ProjectScheme> projectSchemeList = projectSchemeService.queryToList(hashMap,pageableRequest);
        //供应商方案-分阶段
        hashMap.put("jieDuan",jieDuan);
        List<SupplyCompanyScheme> supplyCompanySchemeList = supplyCompanySchemeService.queryToList(hashMap,pageableRequest);
        Map<String, Object> tempMap = new HashMap<>();
        tempMap = service.getContrastSchemeAll(contrastSchemeList,projectSchemeList,supplyCompanySchemeList);
        //设置导出信息
        String fileName = contrastSchemeList.get(0).getProject().getName();
        XSSFWorkbook workbook = service.exportScheme(tempMap);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "电力设计方案对比-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


    @ApiOperation("编辑差异信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        ContrastScheme contrastScheme = JSON.parseObject(json, ContrastScheme.class);
        if (contrastScheme.getId() == null) {
            service.saveAndFlush(contrastScheme);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            ContrastScheme existingProject = service.getByIdLogic(contrastScheme.getId());
            if (existingProject != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(contrastScheme, existingProject, "id");
                // 然后保存更新后的对象
                service.saveAndFlush(existingProject);
            } else {
                // 如果不存在，则保存解析出来的对象
                service.saveAndFlush(contrastScheme);
            }
        }
        return R.ok(contrastScheme);
    }


    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            ContrastScheme contrastScheme = service.findOne(ids[i]);
            if(contrastScheme!=null){
                contrastScheme.setFlag(0);
                service.save(contrastScheme);
            }
        }
        return R.ok();
    }





}

